package pers.hxy.lookweather;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.qweather.sdk.view.HeConfig;

import pers.hxy.lookweather.db.ChinaCitySqliteHelper;
import pers.hxy.lookweather.utils.NetworkStateUtil;
import pers.hxy.lookweather.view.activity.WeatherActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private TextView tvWelcome;
    private Button btnRestart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 账户初始化
        HeConfig.init(Config.QWEATHER_PUBLIC_ID, Config.QWEATHER_PRIVATE_KEY);
        // 切换至免费订阅
        HeConfig.switchToDevService();

        tvWelcome = findViewById(R.id.tv_welcome);

        btnRestart = findViewById(R.id.btn_restart);
        btnRestart.setVisibility(View.GONE);
        btnRestart.setOnClickListener(v -> { checkNetwork(); });

        new Thread(this::init).start();
    }

    private void init() {
        Log.d(TAG, "start init");
        tvWelcome.setText("正在启动，请稍等。。。");
        try (ChinaCitySqliteHelper sqliteHelper = new ChinaCitySqliteHelper(MainActivity.this)) {
            sqliteHelper.readChinaCityListCsvToSqliteDatabase();
        }
        checkNetwork();
    }

    private void checkNetwork() {
        Log.d(TAG, "checkNetwork");
        Log.d(TAG, "wifi available: " + NetworkStateUtil.isWifiAvailable(getApplicationContext()));
        Log.d(TAG, "mobile available: " + NetworkStateUtil.isMobileAvailable(getApplicationContext()));
        if (NetworkStateUtil.isWifiOrMobileAvailable(getApplicationContext())) {
            runOnUiThread(this::initOver);
        } else {
            tvWelcome.setText("请检查你的网络");
            btnRestart.setVisibility(View.VISIBLE);
        }
    }

    private void initOver() {
        Log.d(TAG, "initOver: goto WeatherActivity");
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(this, WeatherActivity.class);
        startActivity(intent);
    }
}
